package com.framework.loippi.controller.api;

import com.framework.loippi.api.utils.ApiUtils;
import com.framework.loippi.entity.Address;
import com.framework.loippi.entity.Patient;
import com.framework.loippi.service.AddressService;
import com.framework.loippi.service.PatientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName PatientController
 * @Description TODO
 * @Author fsociety
 * @Date 29/11/2019 下午2:09
 * @Version 1.0
 */
@Controller("apiPatientController")
@RequestMapping(value = "/api/patient")
@Api(tags = {"患者信息"})
public class PatientController {

    @Resource
    private PatientService patientService;
    @Resource
    private AddressService addressService;

    @RequestMapping(value = "/findAllByUserId.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "根据用户id查询患者", notes = "{}")
    public @ResponseBody
    String findAllPatientByUserId(@Param(value="userId") Integer userId) {
        List<Patient> list = patientService.findAllByUserId(userId);
        return ApiUtils.success(list);
    }

    @RequestMapping(value = "/addPatient.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "添加患者", notes = "{}")
    public @ResponseBody
    String addPatient(@RequestBody JSONObject requestJson) {
        Patient patient = (Patient)JSONObject.toBean(requestJson.getJSONObject("obj"),Patient.class);
        System.out.println(patient);

        Long result = patientService.save(patient);
        Address address = new Address();
        address.setAddress(patient.getAddress());
        address.setName(patient.getName());
        address.setPhone(patient.getPhone());
        address.setUserId(patient.getUserId());
        address.setCreateTime(new Date());
        addressService.save(address);
        return ApiUtils.success(result);
    }

    @RequestMapping(value = "/delete.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "删除患者", notes = "{}")
    public @ResponseBody
    String delete(Long[] ids) {
        patientService.deleteAll(ids);

        return ApiUtils.success();
    }

    @RequestMapping(value = "/edit.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "编辑患者信息", notes = "{}")
    public @ResponseBody
    String edit(@RequestBody JSONObject requestJson) {
        Patient patient = (Patient)JSONObject.toBean(requestJson.getJSONObject("obj"), Patient.class);
        System.out.println(patient);
        patientService.update(patient);

        return ApiUtils.success();
    }
}
